<?php

namespace App\Admin\Actions;

use App\Model\Order;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class QueryDeliver extends RowAction
{
    public $name = '更新物流';

    public function handle(Model $model)
    {
        $deliverSn =  $model->orderInfo->deliver_sn;
        if(!$deliverSn){
            return $this->response()->error('请您先发货')->refresh();
        }
        $deliverInfo = $this->queryDeliverInfo($deliverSn);
        //更新物流
        Order::query()->where('id',$model->orderInfo->id)->update([
           'deliver_info'=>json_encode($deliverInfo,JSON_UNESCAPED_UNICODE)
        ]);
        return $this->response()->success('物流已更新')->refresh();
    }
    /**
     * @return  string
     */
    public function form()
    {
        $this->text('deliver_sn', '请点击下方提交按钮进行更新')->disable();
    }

    public function queryDeliverInfo($deliverSn)
    {
        $host = "https://slypass3.market.alicloudapi.com";
        $path = "/express3";
        $method = "GET";
        $appcode = "4d540e5f243d469eb845bb1d38ebe6a3";//开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE  " . $appcode);
        $querys = "number=$deliverSn";  //参数写在这里
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            $body = json_decode($body,true);
            return $body['data']['info'][0];
        } else {
            return false;
        }
    }
}